#include "StdAfx.h"
#include "FilePath.h"
#include <string>

FilePath::FilePath()
{}

/*
Converts the original filename (set with the function SetPathToOriginal)
to a filename containing the name of the selected view.
*/
int FilePath::GetFileNameToSave(LPTSTR ioBuffer, int inBufSize, bool inAddViewSuffix, ViewID mSelectedViewID) const
{
	if (1 >= mPathToOriginal.size() ||
		(NULL != ioBuffer && 0 >= inBufSize))
	{
		return 0;
	}

	LPCWCH fileNameBegin = &mPathToOriginal[0];
	LPCWCH fileNameEnd = NULL;
	for (size_t i = 0; i < mPathToOriginal.size(); ++i)
	{
		WCHAR ch = mPathToOriginal[i];
		if ('\\' == ch || ':' == ch)
		{
			fileNameBegin = &mPathToOriginal[i+1];
		}
		if ('.' == ch)
		{
			fileNameEnd = &mPathToOriginal[i];
		}
		if ('\0' == ch)
		{
			if (NULL == fileNameEnd || fileNameEnd < fileNameBegin)
			{
				fileNameEnd = &fileNameBegin[i];
			}
			break;
		}
	}

	std::basic_string<TCHAR> name(fileNameBegin, fileNameEnd);
	for (size_t i = 0; ; ++i)
	{
		i = name.find('.');
		if (i == std::string::npos)
		{
			break; 
		}
		name[i] = '_';
	}

	if (inAddViewSuffix)
	{
		const TCHAR* tailPtr = NULL;
		switch (mSelectedViewID)
		{
		case kViewGradient: tailPtr = _T("gradient"); break;
		case kViewGradientSimple: tailPtr = _T("gradient simple"); break;
		case kViewGradientCross: tailPtr = _T("grad upright cross"); break;
		case kViewC2Gradient: tailPtr = _T("C2 gradient"); break;
		case kViewGradientSensitivity: tailPtr = _T("sensitivity"); break;
		case kViewThreshold: tailPtr = _T("threshold"); break;
		case kViewC2Gradient00: tailPtr = _T("C2 grad00"); break;
		case kViewC2Gradient01: tailPtr = _T("C2 grad01"); break;
		case kViewC2Gradient10: tailPtr = _T("C2 grad10"); break;
		case kViewC2Gradient11: tailPtr = _T("C2 grad11"); break;
		};
	
		if (NULL != tailPtr)
		{
			name += _T(" ");
			name += tailPtr;
		}
	}

	if (NULL == ioBuffer)
	{
		return name.length();
	}

	int i = 0;
	for (; i < (int)name.length() && i < inBufSize - 1; ++i)
	{
		ioBuffer[i] = name[i];
	}
	// terminate the string
	ioBuffer[i++] = '\0';
	return i;
}

/*
Saves the filename of the original image in the internal structure.
A modified filename corresponding to the selected view can be retrieved by the function GetFileNameToSave.
*/
void FilePath::SetPathToOriginal(LPCTSTR inPathToOriginal)
{
	size_t len = 0;
	size_t kMaxReasonable = 10000;
	while (len < kMaxReasonable && '\0' != inPathToOriginal[len])
	{
		++len;
	}

	if (0 < len && len < kMaxReasonable)
	{
		mPathToOriginal.resize(len + 1);
		::memcpy(&mPathToOriginal[0], inPathToOriginal, 
			mPathToOriginal.size() * sizeof(mPathToOriginal[0]));
	}
	else
	{
		// only the terminating zero value.
		mPathToOriginal.resize(1);
	}
}